<template>
  <div class="pie-container">
    <div ref="pieChart" style="width: 100%; height: 100%;"></div>
    <p class="total-houses">总房屋数量: {{ totalHouses }}</p>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { sseManager } from '@/api/tool/sse-manager.js';

export default {
  name: "RentalPieChart",
  data() {
    return {
      chartInstance: null,
      debug: true, // 调试开关
      unsubscribe: null,
      option: {
        title: {
          text: '2024年房屋租赁统计',
          left: 'center',
          top: '5%',
          textStyle: {
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: '20%',
          itemGap: 20,
          formatter: name => `{name|${name}}`,
          textStyle: {
            rich: {
              name: {
                width: 60
              }
            }
          }
        },
        series: [
          {
            name: '租赁情况',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '60%'],
            data: [
              { value: 335, name: '已出租' },
              { value: 310, name: '未出租' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            labelLine: {
              show: false
            },
            label: {
              show: false
            }
          }
        ]
      }
    };
  },
  computed: {
    totalHouses() {
      return this.option.series[0].data.reduce((acc, item) => acc + item.value, 0);
    }
  },
  mounted() {
    this.initChart();
    this.subscribeData(); // 订阅 SSE 数据
  },
  beforeDestroy() {
    this.cleanup(); // 销毁资源
  },
  methods: {
    /** 初始化图表 */
    initChart() {
      this.chartInstance = echarts.init(this.$refs.pieChart, null, { renderer: 'svg' });
      this.chartInstance.setOption(this.option);
    },

    /** 订阅 SSE 数据流 */
    subscribeData() {
      const updateHandler = (payload) => {
        if (this.debug) console.log('[RentalPieChart] 收到新数据:', payload);
        this.updateChart(payload);
      };

      this.unsubscribe = sseManager.subscribe('housing_rental_statistics', updateHandler); 
    },

    /** 更新饼图数据 */
    updateChart(payload) {
      if (!payload || typeof payload !== 'object') {
        console.warn('[RentalPieChart] 数据格式错误:', payload);
        return;
      }

      // 假设后端推送的数据格式为：
      // { "已出租": 350, "未出租": 300 }

      const newData = [
        { value: payload['已出租'] || 0, name: '已出租' },
        { value: payload['未出租'] || 0, name: '未出租' }
      ];

      // 更新图表配置
      this.chartInstance.setOption({
        series: [{
          data: newData
        }]
      });

      // 可选：手动更新 option 中的 data（用于 computed 属性）
      this.option.series[0].data = newData;

      if (this.debug) {
        console.log('[RentalPieChart] 图表已更新', newData);
      }
    },

    /** 清理资源 */
    cleanup() {
      if (this.unsubscribe) {
        this.unsubscribe();
      }
      if (this.chartInstance) {
        this.chartInstance.dispose();
        this.chartInstance = null;
      }
    }
  }
};
</script>
<style scoped>
.pie-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px; /* 高度增加以防止重叠 */
  width: 100%;
  padding: 0px; /* 增加内边距以美化布局 */
}

.total-houses {
  font-size: 16px;
  color: #0a0909;
  margin-top: 10px; /* 增加与图表的间距 */

}
</style>